package com.tacademy.android.lbs.location;

import java.io.StringReader;
import java.util.List;

import org.restlet.data.CharacterSet;
import org.restlet.data.Form;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Status;

import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import com.tacademy.android.lbs.location.model.Place;
import com.tacademy.android.lbs.location.model.PlaceParser;

public class VisitRestlet extends ServerResource {
	private LocationService locationService = new LocationService();
	
	public LocationService getLocationService() {
		return locationService;
	}

	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}

	@Post
	public Representation post(Representation representation) {
		Form form = new Form(representation);
		String placeXML = form.getFirstValue("data");
		Representation rep = null;
		try {
			PlaceParser parser = new PlaceParser();
			List<Place> places = parser.parse(new StringReader(placeXML));
			Place place = null;
			if (places != null && places.size() > 0) {
				place = places.get(0);
				locationService.savePlace(place);
			}
			getResponse().setStatus(Status.SUCCESS_CREATED);
			rep = new StringRepresentation(place.xmlString(), MediaType.TEXT_XML, Language.ALL, CharacterSet.UTF_8);
			// rep.setIdentifier(getRequest().getResourceRef().getIdentifier() + place.getKey());
		} catch (Throwable thr) {
			getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
			rep = new StringRepresentation("there was an error creating Location", MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
		}
		return rep;
	}
}
